package com.hdoit.apollo.web.cargo.controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.cargo.model.Cargo;
import com.hdoit.apollo.logical.cargo.model.Category;
import com.hdoit.apollo.logical.cargo.model.Collocation;
import com.hdoit.apollo.logical.cargo.model.Picture;
import com.hdoit.apollo.logical.cargo.model.Standard;
import com.hdoit.apollo.logical.cargo.model.StandardPropertyUser;
import com.hdoit.apollo.logical.cargo.model.StandardUser;
import com.hdoit.apollo.logical.cargo.service.ICargoService;
import com.hdoit.apollo.logical.cargo.service.ICategoryService;
import com.hdoit.apollo.logical.cargo.service.ICollocationService;
import com.hdoit.apollo.logical.cargo.service.IPictureService;
import com.hdoit.apollo.logical.cargo.service.IStandardPropertyUserService;
import com.hdoit.apollo.logical.cargo.service.IStandardService;
import com.hdoit.apollo.logical.cargo.service.IStandardUserService;
import com.hdoit.apollo.logical.common.enums.cargo.CargoState;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.service.ISupplierService;
import com.hdoit.apollo.logical.stock.model.Stock;
import com.hdoit.apollo.logical.stock.model.StockCollocation;
import com.hdoit.apollo.logical.stock.service.IStockCollocationService;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.hdoit.apollo.logical.viewmodel.cargo.CargoSearch;
import com.hdoit.apollo.logical.viewmodel.cargo.CategorySearch;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;

/**
 * @author      humaoshu
 * @email       
 * @createtime  2018年03月31日 15:19:20
 * @comment
 */
@Controller
@RequestMapping(value = "/cargo/cargo/")
public class CargoController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/cargo/cargo/";
    }

    private ICargoService cargoService;
    public ICargoService getCargoService() {
        return cargoService;
    }
    @Resource
    public void setCargoService(ICargoService cargoService) {
        this.cargoService = cargoService;
    }
    
    @Autowired
    private IStandardUserService standardUserService;
    
    @Autowired
    private IStandardService standardServie;

	@Autowired
	private IStandardPropertyUserService standardPropertyUserService;
	
	@Autowired
	private ICollocationService collocationService;
	
	@Autowired
	private IStockService stockService;
	
	@Autowired
	private IStockCollocationService stockCollocationService;
	
	@Autowired
	private IPictureService pictureService;

	@Autowired
	private ISupplierService supplierService;
	
	@Autowired
	private ICategoryService categoryService;
    
    private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="detailed";
    private final String upCargosViewName="upCargos";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String savesViewName="saves";
    
    private final String singleSaveViewName="singleSave";
    
    private final String validateViewName="validate";
    private final String singleDetailedViewName="singleDetailed";
    
    private final String addPicturesViewName="addPictures";
    private final String deletePicturesViewName="deletePictures";
    
    private final String seeDetailedViewName="seeDetailed";
    
    private final String unitViewName="unitSet";
    private final String getCargoInfo="getCargoInfo";
    

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,CargoSearch search,boolean ajaxPost){
    	
    	//Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    	
    	//search.setShopId(shop.getShopId());
    	
        pagerModel.setTotalAmount(cargoService.queryCountMP(search));
        List<Cargo> cargos= cargoService.queryListMPForPC(search,pagerModel);
        
    

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("cargos", cargos);
        model.addAttribute("cargoSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }
    
    @RequestMapping(value = unitViewName, method = { RequestMethod.GET})
    public String unitSet(Model model,String key){
        Cargo cargo=new Cargo();

        
        if(!StringUtils.isEmpty(key)){
            cargo=cargoService.queryModel(key);
        }
        model.addAttribute("cargo", cargo);
        return view(unitViewName);
    }
    

    
    @RequestMapping(value = singleDetailedViewName, method = { RequestMethod.GET})
    public String singleDetailed(Model model,String key){
        Cargo cargo=new Cargo();

        
        List<StandardUser> standardUsers=new ArrayList<StandardUser>();
        if(!StringUtils.isEmpty(key)){
            cargo=cargoService.queryModel(key);
            standardUsers=standardUserService.queryListByCargoId(cargo.getCargoId());
        }
        model.addAttribute("cargo", cargo);
        model.addAttribute("standardUsersJson", JsonUtils.writeValueAsString(standardUsers));
        return view(singleDetailedViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String cargoDetailed(Model model,String key){
        Cargo cargo=new Cargo();

        //List<Collocation> collocations=new ArrayList<Collocation>();
        List<StandardUser> standardUsers=new ArrayList<StandardUser>();
        if(!StringUtils.isEmpty(key)){
            cargo=cargoService.queryModelForView(key);
            //standardUsers=standardUserService.queryListByCargoId(cargo.getCargoId());
        }
        model.addAttribute("cargo", cargo);
        model.addAttribute("standardUsersJson", JsonUtils.writeValueAsString(standardUsers));
        return view(detailedViewName);
    }
    
    
    @RequestMapping(value = seeDetailedViewName, method = { RequestMethod.GET})
    public String seeDetailed(Model model,String key){
        Cargo cargo=new Cargo();

        List<Collocation> collocations=new ArrayList<Collocation>();
        List<StandardUser> standardUsers=new ArrayList<StandardUser>();
        if(!StringUtils.isEmpty(key)){
            cargo=cargoService.queryModelForView(key);
            standardUsers=standardUserService.queryListByCargoId(cargo.getCargoId());
            collocations=collocationService.queryListByCargoId(key);
        }
        model.addAttribute("cargo", cargo);
        model.addAttribute("standardUsers", standardUsers);
        model.addAttribute("collocations", collocations);
        return view(seeDetailedViewName);
    }
    
    
    @ResponseBody
    @RequestMapping(value = validateViewName, method = { RequestMethod.POST },produces = "text/json;charset=UTF-8")
    public String validate(String cargoNos){
    	boolean result=false;
    	List<String> cargoNs = Arrays.asList(cargoNos.split(",")); 
    	List<String> pns=new ArrayList<String>();
    	for (String cargoN : cargoNs) {
            result=cargoService.checkCargoNo(cargoN);
            if(result) {
            	pns.add(cargoN);
            }
        }
    	if(cargoNs.size()>0){
    		return JsonUtils.writeValueAsString(pns);
    	}else{
    		return JsonUtils.writeValueAsString(null);
    	}

    }
    
    @RequestMapping(value = upCargosViewName, method = { RequestMethod.GET})
    public String upCargos(Model model,String key){
        Cargo cargo=new Cargo();
        if(!StringUtils.isEmpty(key)){
            cargo=cargoService.queryModel(key);
        }
        model.addAttribute("cargo", cargo);
        return view(upCargosViewName);
    }
    
    
    //批量上货
    @ResponseBody
    @RequestMapping(value = savesViewName, method = { RequestMethod.POST },produces = "text/json;charset=UTF-8")
    public String saves(@RequestBody List<Cargo> cargos){
        List<StandardUser> standardUsers=new ArrayList<StandardUser>();
        List<StandardPropertyUser> standardPropertyUsers=new ArrayList<StandardPropertyUser>();
        List<Collocation> collocations=new ArrayList<Collocation>();
        List<StockCollocation> stockCollocations=new ArrayList<StockCollocation>();
        List<Stock> stocks=new ArrayList<Stock>();
        int noMark=0;
    	for (Cargo cargo : cargos) {
    		cargo.setCargoId(CommonUtils.getKeyId());
    		cargo.setCreateDate(DateUtils.getCurrent());
    		cargo.setDeleteMark(YesOrNoInteger.no);
    		cargo.setIsHideSalePrice("false");
    		cargo.setIsHideSaleVolume("false");
    		cargo.setIsHideStock("false");
    		cargo.setIsStockWarning("false");

    		cargo.setLowSafetyStock(0);
    		cargo.setHeightSafetyStock(0);
    		cargo.setCargoState(CargoState.onSheleves);
    		cargo.setCreateUserId(getLoginModel().getLoginId());
    		cargo.setCreateUserName(getLoginModel().getLoginName());
    		cargo.setCargoType("库存商品");
    		Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    		cargo.setShopId(shop.getShopId());
    		
    		if(StringUtils.isEmpty(cargo.getCategoryName())) {
    			cargo.setCategoryName("未分类");
    		}else {
        		CategorySearch search=new CategorySearch();
        		search.setCategoryName(cargo.getCategoryName());
        		List<Category> categorys= categoryService.queryListMP(search,null);
        		if(categorys==null||categorys.size()==0) {
        			Category category=new Category();
        			category.setCategoryId(CommonUtils.getKeyId());
        			category.setCategoryName(cargo.getCategoryName());
        			
        			category.setCreateDate(DateUtils.getCurrent());
        			category.setCreateUserId(getLoginModel().getLoginId());
        			category.setCreateUserName(getLoginModel().getLoginName());
        			category.setShopId(shop.getShopId());
        			category.setDeleteMark(YesOrNoInteger.no);
        			category.setModelStatus(ModelStatus.add);
        			categoryService.applyChange(category);
        		}
    		}
    		
    		cargo.setModelStatus(ModelStatus.add);
    		
    		StandardUser standardUser=new StandardUser();
    		standardUser.setCargoId(cargo.getCargoId());
    		standardUser.setStandardId("58f64eea-de23-4a9b-9690-dff38005c5a0");
    		standardUser.setStandardUserId(CommonUtils.getKeyId());
    		standardUser.setCreateDate(DateUtils.getCurrent());
    		standardUser.setDeleteMark(YesOrNoInteger.no);
    		standardUser.setCreateUserId(getLoginModel().getLoginId());
    		standardUser.setCreateUserName(getLoginModel().getLoginName());
    		standardUser.setModelStatus(ModelStatus.add);
    		standardUser.setShopId(shop.getShopId());
    		standardUsers.add(standardUser);
    		
    		StandardPropertyUser standardPropertyUser=new StandardPropertyUser();
    		standardPropertyUser.setStandardUserId(standardUser.getStandardUserId());
    		standardPropertyUser.setStandardPropertyUserId(CommonUtils.getKeyId());
    		standardPropertyUser.setOtherPropertyName(cargo.getProperty());
    		standardPropertyUser.setCreateDate(DateUtils.getCurrent());
    		standardPropertyUser.setDeleteMark(YesOrNoInteger.no);
    		standardPropertyUser.setCreateUserId(getLoginModel().getLoginId());
    		standardPropertyUser.setCreateUserName(getLoginModel().getLoginName());
    		standardPropertyUser.setModelStatus(ModelStatus.add);
    		standardPropertyUser.setShopId(shop.getShopId());
    		
    		standardPropertyUsers.add(standardPropertyUser);
    		
    		Collocation collocation=new Collocation();
    		collocation.setCargoId(cargo.getCargoId());
    		collocation.setCollocationId(CommonUtils.getKeyId());
    		collocation.setCollocationNo(cargo.getCargoNo()+"-"+DateUtils.convertDate2String("mmss",DateUtils.getCurrent()));
    		collocation.setPropertyNameOne(standardPropertyUser.getOtherPropertyName());
    		collocation.setSalePrice(cargo.getSalePrice());
    		collocation.setPurchasePrice(cargo.getPurchasePrice());
    		collocation.setCostPrice(cargo.getCostPrice());
    		collocation.setCombinationPrice(cargo.getCombinationPrice());
    		
    		collocation.setCreateDate(DateUtils.getCurrent());
    		collocation.setDeleteMark(YesOrNoInteger.no);
    		collocation.setCreateUserId(getLoginModel().getLoginId());
    		collocation.setCreateUserName(getLoginModel().getLoginName());
    		collocation.setModelStatus(ModelStatus.add);
    		collocation.setShopId(shop.getShopId());
    		noMark++;
    		collocation.setCollocationNo(cargo.getCargoNo()+noMark);
    		
    		collocations.add(collocation);
    		
    		Stock stock=new Stock();
    		if(cargo.getStockNum()==null) {
    			stock.setStockNum(0.0);
        		stock.setStockDebt(0.0);
    		}else {
    			stock.setStockNum(cargo.getStockNum());
        		stock.setStockDebt(cargo.getStockNum());
    		}
    		stock.setStockId(CommonUtils.getKeyId());
    		stock.setShopId(shop.getShopId());
    		stock.setCargoId(cargo.getCargoId());
    		
    		stock.setCreateDate(DateUtils.getCurrent());
    		stock.setDeleteMark(YesOrNoInteger.no);
    		stock.setModelStatus(ModelStatus.add);
    		
    		stocks.add(stock);
    				
			StockCollocation stockCollocation=new StockCollocation();
			
			if(cargo.getStockNum()==null) {
				stockCollocation.setCollocationDebt(0.0);
				stockCollocation.setCollocationNum(0.0);
    		}else {
    			stockCollocation.setCollocationDebt(cargo.getStockNum());
    			stockCollocation.setCollocationNum(cargo.getStockNum());
    		}
			stockCollocation.setStockCollocationId(CommonUtils.getKeyId());
			stockCollocation.setStockId(stock.getStockId());
			stockCollocation.setCollocationId(collocation.getCollocationId());
			stockCollocation.setCreateDate(DateUtils.getCurrent());
			stockCollocation.setDeleteMark(YesOrNoInteger.no);
			stockCollocation.setModelStatus(ModelStatus.add);
			stockCollocation.setShopId(shop.getShopId());
			stockCollocations.add(stockCollocation);
    		
        }

        if(cargoService.saveCargos(cargos,stocks,standardUsers,standardPropertyUsers,collocations,stockCollocations)){
        	return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }else{
        	return new JsonActionResult(ManageContainer.ERROR).toJson();
        }
       
    }
    
    
    @RequestMapping(value = singleSaveViewName, method = { RequestMethod.POST})
    public String singleSave(Model model,Cargo cargo){
    	
    	//分3种情况保存，初始，一种规格，两种规格
    	
    	 Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    	 List<StandardUser> standardUsers=new ArrayList<StandardUser>();
         List<StandardPropertyUser> standardPropertyUsers=new ArrayList<StandardPropertyUser>();
         List<Collocation> collocations=new ArrayList<Collocation>();
         List<StockCollocation> stockCollocations=new ArrayList<StockCollocation>();
         List<Standard> standards=new ArrayList<Standard>();
         
        if(StringUtils.isEmpty(cargo.getCargoId())){
            cargo.setCargoId(CommonUtils.getKeyId());
            cargo.setCreateDate(DateUtils.getCurrent());
            if(StringUtils.isEmpty(cargo.getCategoryName())) {
    			cargo.setCategoryName("未分类");
    		}
            cargo.setDeleteMark(YesOrNoInteger.no);
            cargo.setCargoState(CargoState.onSheleves);
            cargo.setCreateUserId(getLoginModel().getLoginId());
            cargo.setCreateUserName(getLoginModel().getLoginName());
            cargo.setIsHideSalePrice("false");
    		cargo.setIsHideSaleVolume("false");
    		cargo.setIsHideStock("false");
    		cargo.setIsStockWarning("false");
    		cargo.setLowSafetyStock(0);
    		cargo.setHeightSafetyStock(0);
           
    		cargo.setShopId(shop.getShopId());
            
            cargo.setModelStatus(ModelStatus.add);
        }else{
            cargo.setModifyDate(DateUtils.getCurrent());
            cargo.setModifyUserId(getLoginModel().getLoginId());
            cargo.setModifyUserName(getLoginModel().getLoginName());
            cargo.setModelStatus(ModelStatus.update);
        }
        
        //主表初始库存
        Stock stock=new Stock();
        Double stockNum=0.0;
		stock.setStockId(CommonUtils.getKeyId());
		stock.setShopId(shop.getShopId());
		stock.setCargoId(cargo.getCargoId());
		stock.setStockNum(stockNum);
		stock.setStockDebt(stockNum);
		stock.setCreateDate(DateUtils.getCurrent());
		stock.setDeleteMark(YesOrNoInteger.no);
		stock.setModelStatus(ModelStatus.add);

        String[] costPrices=cargo.getCostPrices().split(",");
        String[] salePrices=cargo.getSalePrices().split(",");
        
        String[] collocationNos=cargo.getCollocationNos().split(",");
        
        if (StringUtils.isEmpty(cargo.getStandNameFirst())&&StringUtils.isEmpty(cargo.getStandNameSecond())){
        	Standard standard=new Standard();
			
			//规格名称，供显示使用
			standard.setStandardId(CommonUtils.getKeyId());
			standard.setStandardName("无");
			standard.setShopId(shop.getShopId());
			standard.setDeleteMark(YesOrNoInteger.no);
			standard.setCreateUserId(getLoginModel().getLoginId());
			standard.setCreateUserName(getLoginModel().getLoginName());
			standard.setCreateDate(DateUtils.getCurrent());
			standard.setModelStatus(ModelStatus.add);
			standards.add(standard);
			
			StandardUser standardUser=new StandardUser();
			standardUser.setCargoId(cargo.getCargoId());
			standardUser.setStandardUserId(CommonUtils.getKeyId());
			standardUser.setStandardId(standard.getStandardId());
			standardUser.setShopId(shop.getShopId());
			standardUser.setDeleteMark(YesOrNoInteger.no);
			standardUser.setCreateUserId(getLoginModel().getLoginId());
			standardUser.setCreateUserName(getLoginModel().getLoginName());
			standardUser.setCreateDate(DateUtils.getCurrent());
			standardUser.setModelStatus(ModelStatus.add);
			
			standardUsers.add(standardUser);
			
			StandardPropertyUser standardPropertyUser=new StandardPropertyUser();
			
			standardPropertyUser.setStandardPropertyUserId(CommonUtils.getKeyId());
			standardPropertyUser.setStandardUserId(standardUser.getStandardUserId());
			standardPropertyUser.setOtherPropertyName("无");
			standardPropertyUser.setShopId(shop.getShopId());
			standardPropertyUser.setDeleteMark(YesOrNoInteger.no);
			standardPropertyUser.setCreateUserId(getLoginModel().getLoginId());
			standardPropertyUser.setCreateUserName(getLoginModel().getLoginName());
			standardPropertyUser.setCreateDate(DateUtils.getCurrent());
			standardPropertyUser.setModelStatus(ModelStatus.add);
			
			standardPropertyUsers.add(standardPropertyUser);
			
			Collocation collocation=new Collocation();
			
			collocation.setCollocationId(CommonUtils.getKeyId());
			collocation.setCargoId(cargo.getCargoId());
			collocation.setPropertyNameOne("无");
			collocation.setCostPrice(Double.parseDouble(costPrices[0]));
			collocation.setSalePrice(Double.parseDouble(salePrices[0]));
			collocation.setPurchasePrice(collocation.getCostPrice());
			collocation.setCollocationNo(collocationNos[0]);
			collocation.setShopId(shop.getShopId());
			collocation.setDeleteMark(YesOrNoInteger.no);
			collocation.setCreateUserId(getLoginModel().getLoginId());
			collocation.setCreateUserName(getLoginModel().getLoginName());
			collocation.setCreateDate(DateUtils.getCurrent());
			collocation.setModelStatus(ModelStatus.add);
			
			collocations.add(collocation);
			
			Double collocationDebt=0.0;			
			StockCollocation stockCollocation=new StockCollocation();
			stockCollocation.setStockCollocationId(CommonUtils.getKeyId());
			stockCollocation.setStockId(stock.getStockId());
			stockCollocation.setCollocationId(collocation.getCollocationId());
			stockCollocation.setCollocationDebt(collocationDebt);
			stockCollocation.setCollocationNum(collocationDebt);
			stockCollocation.setCreateDate(DateUtils.getCurrent());
			stockCollocation.setDeleteMark(YesOrNoInteger.no);
			stockCollocation.setModelStatus(ModelStatus.add);
			stockCollocation.setShopId(shop.getShopId());
			stockCollocations.add(stockCollocation);
			
        }
        
        if (!StringUtils.isEmpty(cargo.getStandNameFirst())) {
			Standard standard=new Standard();
			
			//规格名称，供显示使用
			standard.setStandardId(CommonUtils.getKeyId());
			standard.setStandardName(cargo.getStandNameFirst());
			standard.setShopId(shop.getShopId());
			standard.setDeleteMark(YesOrNoInteger.no);
			standard.setCreateUserId(getLoginModel().getLoginId());
			standard.setCreateUserName(getLoginModel().getLoginName());
			standard.setCreateDate(DateUtils.getCurrent());
			standard.setModelStatus(ModelStatus.add);
			standards.add(standard);
			
			//规格使用保存
			StandardUser standardUser=new StandardUser();
			standardUser.setCargoId(cargo.getCargoId());
			standardUser.setStandardUserId(CommonUtils.getKeyId());
			standardUser.setStandardId(standard.getStandardId());
			standardUser.setShopId(shop.getShopId());
			standardUser.setDeleteMark(YesOrNoInteger.no);
			standardUser.setCreateUserId(getLoginModel().getLoginId());
			standardUser.setCreateUserName(getLoginModel().getLoginName());
			standardUser.setCreateDate(DateUtils.getCurrent());
			standardUser.setModelStatus(ModelStatus.add);
			
			standardUsers.add(standardUser);
			
			
			String[] propertyNames=cargo.getPropertyNameFirsts().split(",");
			
			
			//规格属性保存
			for (int i = 0; i < propertyNames.length; i++) {
				
				StandardPropertyUser standardPropertyUser=new StandardPropertyUser();
				
				standardPropertyUser.setStandardPropertyUserId(CommonUtils.getKeyId());
				standardPropertyUser.setStandardUserId(standardUser.getStandardUserId());
				standardPropertyUser.setOtherPropertyName(propertyNames[i]);
				standardPropertyUser.setShopId(shop.getShopId());
				standardPropertyUser.setDeleteMark(YesOrNoInteger.no);
				standardPropertyUser.setCreateUserId(getLoginModel().getLoginId());
				standardPropertyUser.setCreateUserName(getLoginModel().getLoginName());
				standardPropertyUser.setCreateDate(DateUtils.getCurrent());
				standardPropertyUser.setModelStatus(ModelStatus.add);
				
				standardPropertyUsers.add(standardPropertyUser);
				
				//价格配置信息
				if(StringUtils.isEmpty(cargo.getPropertyNameSeconds())){
					Collocation collocation=new Collocation();
					
					collocation.setCollocationId(CommonUtils.getKeyId());
					collocation.setCargoId(cargo.getCargoId());
					collocation.setPropertyNameOne(propertyNames[i]);
					collocation.setCostPrice(Double.parseDouble(costPrices[i]));
					collocation.setSalePrice(Double.parseDouble(salePrices[i]));
					collocation.setCollocationNo(collocationNos[i]);
					collocation.setShopId(shop.getShopId());
					collocation.setDeleteMark(YesOrNoInteger.no);
					collocation.setCreateUserId(getLoginModel().getLoginId());
					collocation.setCreateUserName(getLoginModel().getLoginName());
					collocation.setCreateDate(DateUtils.getCurrent());
					collocation.setModelStatus(ModelStatus.add);
					
					collocations.add(collocation);
					
					Double collocationDebt=0.0;			
					StockCollocation stockCollocation=new StockCollocation();
					stockCollocation.setStockCollocationId(CommonUtils.getKeyId());
					stockCollocation.setStockId(stock.getStockId());
					stockCollocation.setCollocationId(collocation.getCollocationId());
					stockCollocation.setCollocationDebt(collocationDebt);
					stockCollocation.setCollocationNum(collocationDebt);
					stockCollocation.setCreateDate(DateUtils.getCurrent());
					stockCollocation.setDeleteMark(YesOrNoInteger.no);
					stockCollocation.setModelStatus(ModelStatus.add);
					stockCollocation.setShopId(shop.getShopId());
					stockCollocations.add(stockCollocation);
				}
				
			}
		
			
		}
         
         if (!StringUtils.isEmpty(cargo.getStandNameSecond())&&!StringUtils.isEmpty(cargo.getPropertyNameFirsts())) {
 			Standard standard=new Standard();
 			standard.setStandardId(CommonUtils.getKeyId());
 			standard.setStandardName(cargo.getStandNameSecond());
 			standard.setShopId(shop.getShopId());
 			standard.setDeleteMark(YesOrNoInteger.no);
 			standard.setCreateUserId(getLoginModel().getLoginId());
 			standard.setCreateUserName(getLoginModel().getLoginName());
 			standard.setCreateDate(DateUtils.getCurrent());
 			standard.setModelStatus(ModelStatus.add);
 			standards.add(standard);
 			
 			StandardUser standardUser=new StandardUser();
			standardUser.setCargoId(cargo.getCargoId());
			standardUser.setStandardUserId(CommonUtils.getKeyId());
			standardUser.setStandardId(standard.getStandardId());
			standardUser.setShopId(shop.getShopId());
			standardUser.setDeleteMark(YesOrNoInteger.no);
			standardUser.setCreateUserId(getLoginModel().getLoginId());
			standardUser.setCreateUserName(getLoginModel().getLoginName());
			standardUser.setCreateDate(DateUtils.getCurrent());
			standardUser.setModelStatus(ModelStatus.add);
			standardUsers.add(standardUser);
			
			
			String[] propertyNames=cargo.getPropertyNameSeconds().split(",");
			String[] propertyNameTwos=cargo.getPropertyNameFirsts().split(",");
			for (int i = 0; i < propertyNames.length; i++) {
				
				StandardPropertyUser standardPropertyUserTwo=new StandardPropertyUser();
				
				standardPropertyUserTwo.setStandardPropertyUserId(CommonUtils.getKeyId());
				standardPropertyUserTwo.setStandardUserId(standardUser.getStandardUserId());
				standardPropertyUserTwo.setOtherPropertyName(propertyNames[i]);
				standardPropertyUserTwo.setShopId(shop.getShopId());
				standardPropertyUserTwo.setDeleteMark(YesOrNoInteger.no);
				standardPropertyUserTwo.setCreateUserId(getLoginModel().getLoginId());
				standardPropertyUserTwo.setCreateUserName(getLoginModel().getLoginName());
				standardPropertyUserTwo.setCreateDate(DateUtils.getCurrent());
				standardPropertyUserTwo.setModelStatus(ModelStatus.add);
				
				standardPropertyUsers.add(standardPropertyUserTwo);
				
				Collocation collocation=new Collocation();
				
				collocation.setCollocationId(CommonUtils.getKeyId());
				collocation.setCargoId(cargo.getCargoId());
				collocation.setPropertyNameOne(propertyNames[i]);
				collocation.setPropertyNameTwo(propertyNameTwos[i]);
				collocation.setCostPrice(Double.parseDouble(costPrices[i]));
				collocation.setSalePrice(Double.parseDouble(salePrices[i]));
				collocation.setCollocationNo(collocationNos[i]);
				collocation.setShopId(shop.getShopId());
				collocation.setDeleteMark(YesOrNoInteger.no);
				collocation.setCreateUserId(getLoginModel().getLoginId());
				collocation.setCreateUserName(getLoginModel().getLoginName());
				collocation.setCreateDate(DateUtils.getCurrent());
				collocation.setModelStatus(ModelStatus.add);
				
				collocations.add(collocation);
				
				//子表初始库存
				Double collocationDebt=0.0;			
				StockCollocation stockCollocation=new StockCollocation();
				stockCollocation.setStockCollocationId(CommonUtils.getKeyId());
				stockCollocation.setStockId(stock.getStockId());
				stockCollocation.setCollocationId(collocation.getCollocationId());
				stockCollocation.setCollocationDebt(collocationDebt);
				stockCollocation.setCollocationNum(collocationDebt);
				stockCollocation.setCreateDate(DateUtils.getCurrent());
				stockCollocation.setDeleteMark(YesOrNoInteger.no);
				stockCollocation.setModelStatus(ModelStatus.add);
				stockCollocation.setShopId(shop.getShopId());
				stockCollocations.add(stockCollocation);
				
			}
 		}
         //过滤重复数据，hashMap
         HashMap<String, StandardPropertyUser> map=new HashMap<String, StandardPropertyUser>();
         
         for (StandardPropertyUser standardPropertyUser : standardPropertyUsers) {
			String otherName=standardPropertyUser.getOtherPropertyName();
			
			if (map.containsKey(otherName)) {
				map.get(otherName).setOtherPropertyName(otherName);
			} else {
				map.put(otherName, standardPropertyUser);
			}
		}
         
         List<StandardPropertyUser> standardPropertyUsersSingle=new ArrayList<StandardPropertyUser>();
         
         Iterator<Entry<String, StandardPropertyUser>> iter = map.entrySet().iterator();
         while (iter.hasNext()) {
        	 standardPropertyUsersSingle.add(iter.next().getValue());
			}

        ActionResult actionResult;
        if(cargoService.applyChange(cargo)&&stockService.applyChange(stock)&&
        		standardUserService.applyChanges(standardUsers)&&
        		standardPropertyUserService.applyChanges(standardPropertyUsersSingle)
        		&&stockCollocationService.applyChanges(stockCollocations)&&collocationService.applyChanges(collocations)
        		&&standardServie.applyChanges(standards)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("cargo", cargo);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(singleDetailedViewName);
    }
    

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Cargo cargo){
        if(StringUtils.isEmpty(cargo.getCargoId())){
            cargo.setCargoId(CommonUtils.getKeyId());
            cargo.setCreateDate(DateUtils.getCurrent());
            cargo.setDeleteMark(YesOrNoInteger.no);
            cargo.setCreateUserId(getLoginModel().getLoginId());
            cargo.setCreateUserName(getLoginModel().getLoginName());
            Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    		cargo.setShopId(shop.getShopId());
            
            cargo.setModelStatus(ModelStatus.add);
        }else{
            cargo.setModifyDate(DateUtils.getCurrent());
            cargo.setModifyUserId(getLoginModel().getLoginId());
            cargo.setModifyUserName(getLoginModel().getLoginName());
            cargo.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
        if(cargoService.applyChange(cargo)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("cargo", cargo);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value = addPicturesViewName, method = { RequestMethod.POST ,RequestMethod.GET}, produces = "text/html;charset=UTF-8")
   	public @ResponseBody String addPictures(String pictureIds,String cargoId) {
    	String pictureIdList[]=pictureIds.split(",");
    	
    	System.err.println(pictureIds);
    	System.err.println(cargoId+"货品id");
    	
    	List<Picture> pictures=new ArrayList<Picture>();
    	
    	for (int i = 0; i < pictureIdList.length; i++) {
    		Picture picture=new Picture();
    		System.err.println(pictureIdList[i]+"图片单个id");
    		picture.setPictureId(CommonUtils.getKeyId());
    		picture.setCargoId(cargoId);
    		picture.setFileId(pictureIdList[i]);
    		picture.setMark("cargo");
    		picture.setCreateDate(DateUtils.getCurrent());
    		picture.setDeleteMark(YesOrNoInteger.no);
    		picture.setCreateUserId(getLoginModel().getLoginId());
    		picture.setCreateUserName(getLoginModel().getLoginName());
    		picture.setModelStatus(ModelStatus.add);
    		pictures.add(picture);
    		
		}
    	
    	if (pictureService.applyChanges(pictures)) {
    		
    		 return new JsonActionResult(ManageContainer.SUCCESS).toJson();
    		 
		}
    	
    	
   		
    	return new JsonActionResult(ManageContainer.ERROR).toJson();
   	}
    
    
    
    @RequestMapping(value =deletePicturesViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String deletePicture(String key){
        if(pictureService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(cargoService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    @RequestMapping(value = getCargoInfo, method = { RequestMethod.GET},produces = "text/html;charset=UTF-8")
    public @ResponseBody String getCargoInfo(Model model,String cargoId){
    	
        Cargo cargo=cargoService.queryModel(cargoId);
        return "{\"data\":"+JsonUtils.writeValueAsString(cargo)+"}";
    }
}